package com.huirui.server.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huirui.server.constant.ProductType;
import com.huirui.server.exception.ProductTransactionalException;
import com.huirui.server.mapper.NewcomerAreaProductMapper;
import com.huirui.server.pojo.dto.NewcomerAreaProductDto;
import com.huirui.server.pojo.entity.NewcomerAreaProduct;
import com.huirui.server.pojo.entity.Product;
import com.huirui.server.pojo.entity.ProductSpecification;
import com.huirui.server.pojo.result.PageResult;
import com.huirui.server.pojo.vo.NewcomerAreaProductVo;
import com.huirui.server.service.NewcomerAreaProductService;
import com.huirui.server.service.ProductService;
import com.huirui.server.service.ProductSpecificationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yujun
 * @description 针对表【t_newcomer_area_product】的数据库操作Service实现
 * @createDate 2025-11-06 17:21:19
 */
@Service
@Slf4j
public class NewcomerAreaProductServiceImpl extends ServiceImpl<NewcomerAreaProductMapper, NewcomerAreaProduct>
        implements NewcomerAreaProductService {

    @Resource
    private ProductService productService;

    @Resource
    private ProductSpecificationService productSpecificationService;

    @Override
    @Transactional
    public void addProduct(NewcomerAreaProductDto newcomerAreaProductDto) {
        var productId = newcomerAreaProductDto.getProductId();
        // 查询商品状态
        // 合并后的代码（替代原 exists() 和 productType 查询）
        Product product = productService
                .lambdaQuery()
                .select(Product::getProductType) // 只查需要的字段，减少开销
                .eq(Product::getId, productId)
                .oneOpt()
                .orElseThrow(() -> new ProductTransactionalException("商品不存在！"));

        // 校验商品类型
        if (product.getProductType() != ProductType.GENERAL_PRODUCT) {
            throw new ProductTransactionalException("商品状态异常！");
        }
        // 更新商品类型
        productService
                .lambdaUpdate()
                .eq(Product::getId, productId)
                .set(Product::getProductType, ProductType.NEWCOMER_PRODUCT)
                .set(Product::getUpdateTime, LocalDateTime.now())
                .set(Product::getProductStatus, 0)
                .update();
        // 更新商品规格
        List<ProductSpecification> productSpecifications = new ArrayList<>();
        newcomerAreaProductDto.getSpecifications().forEach(specificationVo -> {
            ProductSpecification productSpecification = new ProductSpecification();
            productSpecification.setId(specificationVo.getProductSpecificationId());
            productSpecification.setPromotionalPrice(specificationVo.getPromotionalPrice());
            productSpecification.setStock(Math.toIntExact(specificationVo.getStock()));
            productSpecification.setAvailableStock(Math.toIntExact(specificationVo.getStock()));
            productSpecification.setUpdateTime(LocalDateTime.now());
            productSpecifications.add(productSpecification);
        });
        productSpecificationService
                .updateBatchById(productSpecifications);
        // 保存到商品关联表
        NewcomerAreaProduct newcomerAreaProduct = new NewcomerAreaProduct();
        newcomerAreaProduct.setProductId(productId);
        newcomerAreaProduct.setCreateTime(LocalDateTime.now());
        newcomerAreaProduct.setUpdateTime(LocalDateTime.now());
        save(newcomerAreaProduct);
    }

    @Override
    public PageResult<NewcomerAreaProductVo> listNewcomerProduct(String keyword, Long page, Long pageSize) {
        IPage<NewcomerAreaProductVo> iPage = new Page<>(page, pageSize);
        iPage = baseMapper.listNewcomerProduct(keyword, iPage);
        return PageResult.from(iPage);
    }

    @Override
    public void updateProduct(NewcomerAreaProductDto newcomerAreaProductDto) {
        // 合并后的代码（替代原 exists() 和 productType 查询）
        Product product = productService
                .lambdaQuery()
                .select(Product::getProductType) // 只查需要的字段，减少开销
                .eq(Product::getId, newcomerAreaProductDto.getProductId())
                .oneOpt()
                .orElseThrow(() -> new ProductTransactionalException("商品不存在！"));

        // 校验商品类型
        if (product.getProductType() != ProductType.NEWCOMER_PRODUCT) {
            throw new ProductTransactionalException("商品状态异常！");
        }
        // 更新商品规格
        List<ProductSpecification> productSpecifications = new ArrayList<>();
        newcomerAreaProductDto.getSpecifications().forEach(specificationVo -> {
            ProductSpecification productSpecification = new ProductSpecification();
            productSpecification.setId(specificationVo.getProductSpecificationId());
            productSpecification.setPromotionalPrice(specificationVo.getPromotionalPrice());
            productSpecification.setStock(Math.toIntExact(specificationVo.getStock()));
            productSpecification.setAvailableStock(Math.toIntExact(specificationVo.getStock()));
            productSpecification.setUpdateTime(LocalDateTime.now());
            productSpecifications.add(productSpecification);
        });
        productSpecificationService
                .updateBatchById(productSpecifications);

        lambdaUpdate()
                .set(NewcomerAreaProduct::getUpdateTime, LocalDateTime.now())
                .eq(NewcomerAreaProduct::getProductId, newcomerAreaProductDto.getProductId())
                .update();
    }

    @Override
    @Transactional
    public void deleteProduct(Long productId) {
        // 合并后的代码（替代原 exists() 和 productType 查询）
        Product product = productService
                .lambdaQuery()
                .select(Product::getProductType) // 只查需要的字段，减少开销
                .eq(Product::getId, productId)
                .oneOpt()
                .orElseThrow(() -> new ProductTransactionalException("商品不存在！"));

        // 校验商品类型
        if (product.getProductType() != ProductType.NEWCOMER_PRODUCT) {
            throw new ProductTransactionalException("商品状态异常！");
        }
        // 更改商品状态
        productService
                .lambdaUpdate()
                .eq(Product::getId, productId)
                .set(Product::getProductType, ProductType.GENERAL_PRODUCT)
                .set(Product::getProductStatus, 1)
                .set(Product::getUpdateTime, LocalDateTime.now())
                .update();
        // 删除关联关系
        lambdaUpdate()
                .eq(NewcomerAreaProduct::getProductId, productId)
                .remove();

    }

    @Override
    public List<NewcomerAreaProductVo> listProduct(Long page, Long pageSize) {
        IPage<NewcomerAreaProductVo> iPage = new Page<>(page, pageSize);
        return baseMapper.listProduct(iPage);
    }
}




